package com.jzoffer;

/*
* 输入两个链表，找出它们的第一个公共结点。（
* 注意因为传入数据是链表，所以错误测试数据的提示是用其他方式显示的，保证传入数据是正确的
* */
public class TheFirstCommonNode {

    public static void main(String[] args) {
        ListNode t1 = new ListNode(1);
        ListNode t2 = new ListNode(2);
        ListNode t3 = new ListNode(3);
        ListNode t4 = new ListNode(4);
        ListNode t5 = new ListNode(5);

        ListNode v1 = new ListNode(8);
        ListNode v2 = new ListNode(9);

        t1.next = t2;
        t2.next = t3;
        t3.next = t4;
        t4.next = t5;
        v1.next = v2;
//        v2.next = t4;

        ListNode firstCommonNode = findFirstCommonNode(t1, v1);
        System.out.println(firstCommonNode.val);

    }

    public static ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2){
        if(pHead1 == null || pHead2 == null){
            return null;
        }

        ListNode p1 = pHead1;
        ListNode p2 = pHead2;

        while (p1 != p2){
            p1 = p1.next == null ? pHead2:p1.next;
            p2 = p2.next == null ? pHead1:p2.next;
        }
        return p1;
    }
}
